﻿using System;
using Core.AdminUser;
using Core.Authenticated;
using Core.Library;

namespace CMS.Controls.AdminUser
{
    public partial class ChangePassword : AuthenticatedControl
    {
        private int _adminUserId;

        protected void Page_Load(object sender, EventArgs e)
        {
            _adminUserId    = Utils.GetIdFromRequestString(Utils.UserId, 0);

            ltMessage.Text = MessageUtility.ShowMessage(null, _adminUserId > 0 
                                        ? string.Format("Thành viên {0}", GetAdminUser(_adminUserId)) 
                                        : string.Format("Thành viên {0}", CurrentUser.FullName), MessageType.Information);
        }

        private string GetAdminUser(int id)
        {
            try
            {
                var user = AdminUserController.AdminUser_GetById(id);
                return user != null ? user.FullName : string.Empty;
            }
            catch { return string.Empty; }            
        }

        private void UserChangePassword(int currentUserId)
        {
            bool isDuplicate = txtPassword.Text.Trim() == txtRepassword.Text.Trim();

            if (isDuplicate)
            {
                AdminUserController.AdminUser_UpdatePassword(currentUserId, SecurityUtility.MD5Encrypt(txtPassword.Text));
                ltMessage.Text = MessageUtility.ShowMessage(null, "Đổi mật khẩu thành công!", MessageType.Success);
            }
            else            
                ltMessage.Text = MessageUtility.ShowMessage(null, "Không khớp mật khẩu. Vui lòng nhập lại!", MessageType.Warning);            
        }

        protected void BtnSave(object sender, EventArgs e)    
        {
            try
            {
                UserChangePassword(_adminUserId > 0 ? _adminUserId : CurrentUser.AdminUserId);
            }
            catch (Exception ex)
            {
                ltMessage.Text = MessageUtility.ShowMessage(null, ex.Message, MessageType.Failure);
            }
        }                        
    }
}